<link rel="stylesheet" href="/static/css/up_style.css">
<script src="/static/js/jquery.fcup.js"></script>
<div id="task-modal">
  <div class="task-create-editor" id="task-create-editor">
    <ul class="es-step es-step-3 clearfix" id="task-create-step">
      #--<!--<li :class="getTabStyle(1)">-->
        <!--<span class="number">1</span> 选择教学手段-->
      <!--</li>-->--#
      <li :class="getTabStyle(1)">
        <span class="number">1</span> 设置内容
      </li>
      <li :class="getTabStyle(2)">
        <span class="number">2</span> 设置完成条件
      </li>
    </ul>
    <!--根据类型添加具体课程-->
    <div v-show="tabNum==1">
      <form class="form-horizontal" id="step2-form" novalidate="novalidate">
        <div class="form-group">
          <div class="col-sm-2 control-label">
            <label for="title" class="control-label-required">标题名称</label>
          </div>
          <div class="col-sm-10">
            <input v-model="task.name" id="title" class="form-control" type="text">
          </div>
        </div>
        <!--视频-->
        <div v-show="tabTaskType=='video'">
          <div class="form-group">
            <div class="col-sm-2 control-label">
              <label for="media" class="style control-label-required">视频资源</label>
            </div>
            <div class="col-sm-10">
              <div class="file-chooser-main" id="media">
                <div class="file-chooser-nav">
                  <ul class="nav nav-pills nav-pills-sm nav-pills-gray mb0" id="material">
                    <li class="active">
                      <a href="#uploadMaterial" data-toggle="tab">上传资料</a>
                    </li>
                    <li>
                      <a @click="loadNoUse" href="#chooseMaterial" data-toggle="tab">从已有文件选择</a>
                    </li>
                  </ul>
                </div>
                <div class="tab-content">
                  <div id="uploadMaterial" class="tab-pane file-chooser-tab active">
                    <div class="uploader-content"></div>
                  </div>
                  <div id="chooseMaterial" class="tab-pane file-chooser-tab">
                    <div>
                      <div v-if="noUseMaterials.length<=0" align="center">
                        <strong>没有空闲的课程资源，请上传！</strong>
                      </div>
                      <select v-model="noUseIndex" v-else-if="noUseMaterials.length>0" class="form-control">
                        <template v-for="(nu, index) in noUseMaterials">
                          <option :value="index">{{nu.filename}}</option>
                        </template>
                      </select>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-2 control-label for-video-type">
              <label class="control-label-required">视频时长</label>
            </div>
            <div class="col-sm-10">
              <input v-model="task.minute" class="form-control width-150 js-length">
              <span class="mhs">分</span>
              <input v-model="task.second" class="form-control width-150 js-length">
              <span class="mhs">秒</span>
            </div>
          </div>
        </div>
      </form>
    </div>
    <!--设置课程完成条件-->
    <div v-show="tabNum==2">
      <form class="form-horizontal" id="step3-form">
        <!--视频-->
        <div v-if="tabTaskType=='video'">
          <div class="form-group">
            <div class="col-sm-2 control-label">
              <label>完成条件</label>
            </div>
            <div class="col-sm-4">
              <select id="finish-condition" v-model="task.goal" class="form-control">
                <option value="0" selected="">学习到最后</option>
                <option value="1">学习时长</option>
              </select>
            </div>
          </div>
        </div>

        <div v-show="tabTaskType=='ppt' || task.goal==1" class="form-group" id="condition-group">
          <div class="col-xs-2 control-label">
            <label for="finishDetail">至少观看</label>
          </div>
          <div class="col-xs-4">
            <input id="finishDetail" class="form-control" v-model="task.minTime">
          </div>
          <div class="col-xs-4">
            <p class="form-control-static">分</p>
          </div>
        </div>
        #-- <!--<div class="form-group">
          <div class="col-md-10 col-md-offset-2 radios">
            <label>
              <input type="checkbox" name="isOptional" v-model="task.electives">
              设为选修
            </label>
            <span class="color-gray">选修任务是否学习，不会影响下一任务的解锁，学习结果不会计入学习进度、学习统计中。在课程页面的目录中，将不会显示选修任务。</span>
          </div>
        </div>--> --#
      </form>
    </div>
  </div>
  <div class="modal-footer-inline">
    <button v-show="tabNum > 1" class="btn btn-default" @click="tabPrev">上一步</button>
    <button v-show="tabNum < 2" class="btn btn-default" @click="tabNext">下一步</button>
    <template v-if="tabNum == 2">
      <button class="btn btn-primary" @click="saveOrUpdate(0)">保存</button>
      <button class="btn btn-info" @click="saveOrUpdate(1)">发布</button>
    </template>
  </div>
</div>
<video style="display:none;" controls="controls" id="upVideo"></video>
<script>
  var types = ['video', 'ppt'];
  var ST = new Vue({
    el: '#task-modal',
    data: {
      tabNum: 1,
      isSave: false,
      tabTaskType: types[tm.changeTask.type] || 'video',
      progress: -1,
      noUseMaterials: [],
      noUseIndex: -1,
      task: $.extend({}, tm.changeTask),
      shardSize: 0.8 * 1024 * 1024 // 切片尺寸
    },
    computed: {
      videoTip: function () {
        if (this.task.materialId != null) {
          return '<span style="color: #000;">'+this.task.material.filename+'</span>'
        } else {
          return '请选择视频上传!'
        }
      }
    },
    watch: {
      noUseIndex: function (nv) {
        var self = this;
        if (nv >= 0) {
          this.$set(this.task, 'material', this.noUseMaterials[nv]);
          this.$set(this.task, 'materialId', this.noUseMaterials[nv].id);
          this.setTime(true);
        }
      }
    },
    methods: {
      // 模态框步奏导航样式
      getTabStyle: function (num) {
        if (this.tabNum >= num) {
          return 'done doing';
        }
        return '';
      },
      tabNext: function () {
        if (this.checkForm(this.tabNum)) {
          this.tabNum++;
        }
      },
      tabPrev: function () {
        this.tabNum--;
      },
      uploadVideo: function(result) {
        if (result.success && result.code !== 206) {
          this.$set(this.task, 'material', result.payload);
          this.$set(this.task, 'materialId', result.payload.id);
          this.setTime(true);
        }
      },
      saveOrUpdate: function (status) {
        if (this.checkForm(2)) {
          var self = this;
          var add = true;
          var url = '/course/set/task/${kid}/add';
          if (this.task.id > 0) {
            add = false;
            url = '/course/set/task/${kid}/change/' + this.task.id;
          }
          this.task.type = types.indexOf(this.tabTaskType);
          if (this.task.minTime) this.task.minTime = parseInt(this.task.minTime) * 60;
          this.task.duration = parseInt(this.task.minute) * 60 + parseInt(this.task.second);
          this.task.electives = this.task.electives ? 1 : 0;
          this.task.status = status || 0;
          $.post(url, this.task, function (data) {
            if (data.success) {
              if (add) {
                tm.tasks.push($.extend(data.payload, self.task));
              } else {
                $.extend(tm.changeTask, self.task);
              }
              ST.isSave = true;
              closeModal_();
            }
          });
        }
      },
      loadNoUse: function () {
        var self = this;
        $.post("/course/material/api/${kid}/nouse", function (data) {
          if (data.success) {
            self.noUseMaterials = data.payload;
          }
        });
      },
      setTime: function (fromVideo) {
        var self = this;
        if (fromVideo) {
          getVideoTime(this.task.material.path, function (time) {
            self.$set(self.task, 'duration', parseInt(time));
            self.setTime();
            self.progress = 100;
          });
        }
        this.$set(this.task, 'minute', parseInt(this.task.duration / 60) || 0);
        this.$set(this.task, 'second', this.task.duration % 60 || 1);
        this.$set(this.task, 'minTime', parseInt(this.task.minTime / 60) || 1);
      },
      checkForm: function (stage) {
        var task = this.task;
        if (stage === 1) {
           if (isEmpty(task.name)) {
             layer.msg("任务标题不能为空！", {time: 1200});
           } else if (task.materialId==null || task.materialId<=0) {
             layer.msg("任务资源必须选择！", {time: 1200});
           } else if (task.minute == null || task.minute <= 0 || task.second == null || task.second <= 0) {
             layer.msg("任务视频时间不能为空！", {time: 1200});
           } else {
             return true;
           }
        } else if (stage === 2) {
          if (task.goal == 1 && parseInt(task.minTime) <= 0) {
            layer.msg("至少观看时间不能为空！", {time: 1200});
          } else {
            return true;
          }
        }
        return false;
      }
    },
    created: function () {
      this.setTime();
    }
  });

  function closeModal_() {
    if (ST.isSave) {
      clearModal();
    } else {
      layer.confirm('还有数据没被保存,确定要退出?', {
        icon: 3,
        title:'提示'
      }, function (i) {
        clearModal();
        layer.close(i);
      });
    }
  }

  function clearModal() {
    tm.changeTask = {
      goal: 0,
      electives: 0
    };
    ST.isSave = false;
    ST.noUseMaterials = [];
    ST.noUseIndex = -1;
    $('#modal').modal('hide');
  }

  $('.js-course-tasks-item').click(function () {
    $('.js-course-tasks-item').removeClass('active');
    $(this).addClass('active');
    ST.tabTaskType = $(this).data('type');
  });

  !(function ($) {
    $.each($('.js-course-tasks-item'), function (i, v) {
      if (ST.tabTaskType == $(v).data('type')) {
        $(v).addClass('active');
      }
    })
  })(window.$);

  // 获取视频的长度
  function getVideoTime(src, fun) {
    var video = document.getElementById("upVideo");
    video.src = src;
    video.oncanplaythrough = function (ev) {
      fun ? fun(ev.target.duration) : null;
    }
  }

  // 切片上传 这插件代码写的真垃圾 用用吧没办法
  $.fcup({
    updom: '.uploader-content',
    upid: 'upid',
    shardsize: '1.5',
    upmaxsize : '120',  // 允许上传文件的最大尺寸
    upstr: '选择mp4视频文件',
    upurl: '/video/upload',
    uptype: 'mp4',
    errmaxup: '上传文件大于120MB',
    errtype: '请上传mp4文件',
    kid: tm.kid,
    upcallback : function(result) {
      ST.uploadVideo(JSON.parse(result));
    }
  });
</script>